import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/user'

// 创建axios实例
const instance = axios.create({
  baseURL: '/api',
  timeout: 600000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response
  },
  async (error) => {
    const { response } = error
    
    if (response?.status === 401) {
      // token过期，尝试刷新
      const userStore = useUserStore()
      const refreshSuccess = await userStore.refreshToken()
      
      if (refreshSuccess) {
        // 刷新成功，重试原请求
        const config = error.config
        config.headers.Authorization = `Bearer ${userStore.token}`
        return instance.request(config)
      } else {
        // 刷新失败，跳转到登录页
        ElMessage.error('登录已过期，请重新登录')
        userStore.logout()
        window.location.href = '/login'
      }
    } else if (response?.status === 403) {
      ElMessage.error('权限不足')
    } else if (response?.status === 404) {
      ElMessage.error('请求的资源不存在')
    } else if (response?.status >= 500) {
      ElMessage.error('服务器内部错误')
    } else if (error.message === 'Network Error') {
      ElMessage.error('网络连接失败')
    } else {
      ElMessage.error(error.message || '请求失败')
    }
    
    return Promise.reject(error)
  }
)

export default instance
